const { app, dialog } = require('electron')
const http = require('http')
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')

//
// 下载函数
exports.downloadFile = (url, window) => {
  const arr = url.split('/')

  // 弹出文件保存对话框
  const savePath = dialog.showOpenDialogSync(window, {
    // defaultPath: path.join(app.getPath('downloads'), arr[arr.length - 1]),
    defaultPath: app.getPath('downloads'),
    // defaultPath: arr[arr.length - 1],
    properties: ['openDirectory'],
    filters: [
      { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
      { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
      { name: 'Custom File Type', extensions: ['as'] },
      { name: 'All Files', extensions: ['*'] },
    ],
  })

  if (!savePath) return console.log('File download cancelled.')

  const file = fs.createWriteStream(savePath[0] + '\\' + arr[arr.length - 1])

  http
    .get(url, function (response) {
      response.pipe(file)
      file.on('finish', function () {
        file.close()
        console.log('File downloaded successfully:', savePath)
      })
    })
    .on('error', function (err) {
      fs.unlink(savePath)
      console.error('Error downloading file:', err.message)
    })
}

//
//
// 生成唯一的设备标识符并保存到 public 文件夹
exports.generateAndSaveDeviceId = () => {
  let deviceIdFilePath

  // 判断开发环境或生产环境
  if (!app.isPackaged) {
    deviceIdFilePath = path.join(__dirname, '../public/deviceIcon.ico') // 开发环境
  } else {
    // 生产环境：获取可执行文件所在目录，而不是可执行文件路径本身
    deviceIdFilePath = path.join(
      path.dirname(app.getPath('exe')),
      'deviceIcon.ico'
    ) // 生产环境 - 修复路径
  }

  // 确保文件夹路径存在
  const directoryPath = path.dirname(deviceIdFilePath)
  if (!fs.existsSync(directoryPath)) {
    fs.mkdirSync(directoryPath, { recursive: true })
  }

  // 检查文件是否存在，若不存在则生成并保存新的 UUID
  if (!fs.existsSync(deviceIdFilePath)) {
    const deviceId = crypto.randomUUID
      ? crypto.randomUUID()
      : crypto.randomBytes(16).toString('hex') // 兼容旧版本

    fs.writeFileSync(deviceIdFilePath, deviceId, 'utf-8')
    console.log('Device ID generated and saved:', deviceId)
    return ''
  } else {
    // 如果文件已存在，直接读取文件中的设备 ID
    const deviceId = fs.readFileSync(deviceIdFilePath, 'utf-8')
    console.log('Device ID already exists:', deviceId)
    return deviceId
  }
}
